package com.jarvan.controller;

import com.alibaba.fastjson.JSON;
import com.jarvan.dto.TrainDto;
import com.jarvan.dto.TrainsDto;
import com.jarvan.enums.ResultEnum;
import com.jarvan.exception.TrainException;
import com.jarvan.form.TrainForm;
import com.jarvan.model.Trains;
import com.jarvan.service.impl.TrainsServiceImpl;
import com.jarvan.utils.ResultVoUtil;
import com.jarvan.utils.TrainsSerialize;
import com.jarvan.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Api(value = "后台火车增删改查")
@RestController
@RequestMapping("/admin/train")
public class AdminTrainController {

    @Autowired
    private TrainsServiceImpl trainsService;

    @ApiOperation(value = "新增火车")
    @PostMapping("/save")
    public ResultVo<TrainDto> create(@Valid @RequestBody TrainForm trainForm) {
        log.info("[新增列车]  trainForm={}", trainForm);
        Trains result = trainsService.save(trainForm);
        if (result == null){
            log.error("[新增火车]  添加失败  trainForm={}", trainForm);
            throw new TrainException(ResultEnum.ADD_FIALURE.getCode(), ResultEnum.ADD_FIALURE.getMessage());
        }
        TrainDto dto = new TrainDto();
        BeanUtils.copyProperties(result, dto);
        dto.setStationInfos(JSON.parseArray(result.getStations(),String.class));
        return ResultVoUtil.success(dto);
    }

    @GetMapping("/list")
    public ResultVo<TrainsDto> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                    @RequestParam(value = "size", defaultValue = "10") Integer size){
        Page<Trains> result = trainsService.findAll(PageRequest.of(page-1, size));
        TrainsDto trainsDto = new TrainsDto();
        List<Trains> list = result.getContent();

        trainsDto.setTrainsList(TrainsSerialize.convert(list));
        trainsDto.setTotal(result.getTotalElements());

        return ResultVoUtil.success(trainsDto);
    }

    @GetMapping("/find/{trainId}")
    public ResultVo<List<TrainDto>> findById(@PathVariable String trainId){
        if (trainId.isEmpty()){
            log.error("[列车查询]  trainId={}", trainId);
            throw new TrainException(ResultEnum.PARAM_ERROR.getCode(), "trainId不存在");
        }
        Trains trains;
        try {
            trains = trainsService.findOne(trainId);
        } catch (TrainException e){
            return ResultVoUtil.error(e.getCode(), e.getMessage());
        }
        TrainDto dto = new TrainDto();
        List<TrainDto> dtoList = new ArrayList<>();
        BeanUtils.copyProperties(trains, dto);
        dto.setStationInfos(JSON.parseArray(trains.getStations(), String.class));
        dtoList.add(dto);
        return ResultVoUtil.success(dtoList);
    }

    @GetMapping("/findByCity")
    public ResultVo<List<TrainDto>> findByCity(@RequestParam("start") String start, @RequestParam("end") String end){
        List<Trains> list = trainsService.findByStartAndEnd(start, end);

        List<TrainDto> dtoList = TrainsSerialize.convert(list);
        return ResultVoUtil.success(dtoList);
    }

    @GetMapping("/delete/{trainId}")
    public ResultVo<Trains> delete(@PathVariable String trainId){
        if (trainId.isEmpty()){
            log.error("[列车删除]  trainId={}", trainId);
            throw new TrainException(ResultEnum.PARAM_ERROR.getCode(), "trainId不存在");
        }
        trainsService.remove(trainId);
        return ResultVoUtil.success();
    }

    @GetMapping("/recover/{trainId}")
    public ResultVo<Trains> recover(@PathVariable String trainId){
        if (trainId.isEmpty()){
            log.error("[列车恢复]  trainId={}", trainId);
            throw new TrainException(ResultEnum.PARAM_ERROR.getCode(), "trainId不存在");
        }
        trainsService.recover(trainId);
        return ResultVoUtil.success();
    }

    @GetMapping("/findByStatus")
    public ResultVo<TrainsDto> findByStatus(@RequestParam("trainStatus") Integer trainStatus,
                                            @RequestParam(value = "page", defaultValue = "1") Integer page,
                                            @RequestParam(value = "size", defaultValue = "10") Integer size){
        Page<Trains> page1 = trainsService.findByStatus(trainStatus, PageRequest.of(page-1, size));
        List<Trains> list = page1.getContent();
        TrainsDto trainsDto = new TrainsDto();
        trainsDto.setTrainsList(TrainsSerialize.convert(list));
        trainsDto.setTotal(page1.getTotalElements());
        return ResultVoUtil.success(trainsDto);
    }
}